import json
import os
from typing import Dict, Any

class ConfigManager:
    """配置管理器，用于读取和管理config.json配置文件中的AI模型配置"""
    
    def __init__(self, config_path: str = None):
        """
        初始化配置管理器
        :param config_path: 配置文件路径，默认为UI/config.json
        """
        if config_path is None:
            # 默认路径：从roothealer目录到UI/config.json
            current_dir = os.path.dirname(__file__)  # backend/core/roothealer
            project_root = os.path.join(current_dir, '..', '..', '..')  # 回到项目根目录
            config_path = os.path.join(project_root, 'UI', 'config.json')
        
        self.config_path = config_path
        self._config = None
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self._config = json.load(f)
        except FileNotFoundError:
            print(f"❌ 配置文件不存在: {self.config_path}")
            self._config = {}
        except json.JSONDecodeError as e:
            print(f"❌ 配置文件JSON格式错误: {e}")
            self._config = {}
        except Exception as e:
            print(f"❌ 配置文件加载失败: {e}")
            self._config = {}
    
    def get_current_provider(self) -> str:
        """获取当前使用的LLM提供商"""
        return self._config.get('current_provider', 'local')
    
    def get_provider_config(self, provider_name: str = None) -> Dict[str, Any]:
        """
        获取指定提供商的配置
        :param provider_name: 提供商名称，如果为None则使用当前提供商
        :return: 提供商配置字典
        """
        if provider_name is None:
            provider_name = self.get_current_provider()
        
        providers = self._config.get('providers', {})
        provider_config = providers.get(provider_name, {})
        
        # 合并默认参数
        default_params = {
            'temperature': self._config.get('temperature', 0.1),
            'top_p': self._config.get('top_p', 0.7),
            'max_tokens': self._config.get('max_tokens', 2048),
            'frequency_penalty': self._config.get('frequency_penalty', 0.0),
            'presence_penalty': self._config.get('presence_penalty', 0.0),
            'repeat_penalty': self._config.get('repeat_penalty', 1.0),
            'stream': self._config.get('stream', True),
            'timeout': self._config.get('timeout', 300),
            'proxy': self._config.get('proxy', None),
            'safe_mode': self._config.get('safe_mode', True),
            'input_encoding': self._config.get('input_encoding', 'auto')
        }
        
        provider_config.update(default_params)
        return provider_config
    
    def get_qwen_config(self) -> Dict[str, str]:
        """获取 API配置（兼容旧版本）"""
        current_provider = self.get_current_provider()
        provider_config = self.get_provider_config(current_provider)
        
        # 如果是本地Ollama部署
        if provider_config.get('type') == 'ollama':
            base_url = provider_config.get('api_url', 'http://localhost:11434')
            # 检查是否有chat_endpoint配置
            chat_endpoint = provider_config.get('chat_endpoint', '/api/chat')
            api_url = base_url.rstrip('/') + chat_endpoint
            return {
                'api_url': api_url,
                'api_key': None,  # Ollama通常不需要API Key
                'model': provider_config.get('model', 'qwen7b:latest')
            }
        # 如果是OpenAI兼容的API
        elif provider_config.get('type') == 'openai':
            base_url = provider_config.get('api_url', 'https://api.openai.com')
            # 检查是否有chat_endpoint配置，如果没有则使用默认值
            chat_endpoint = provider_config.get('chat_endpoint', '/v1/chat/completions')
            api_url = base_url.rstrip('/') + chat_endpoint
            return {
                'api_url': api_url,
                'api_key': provider_config.get('api_key', ''),
                'model': provider_config.get('model', 'gpt-3.5-turbo')
            }
        else:
            # 默认配置
            return {
                'api_url': 'http://localhost:11434/api/chat',
                'api_key': None,
                'model': 'qwen7b:latest'
            }
    
    def reload_config(self):
        """重新加载配置文件"""
        self._load_config()

# 全局配置管理器实例
config_manager = ConfigManager()
